<template>
  <div class="product-reviews">
    <!-- 评分统计 -->
    <div class="rating-stats bg-gray-50 p-4 rounded-lg mb-4">
      <div class="flex items-center">
        <div class="text-center mr-8">
          <div class="text-3xl font-bold text-orange-500">
            {{ stats.averageRating }}
          </div>
          <div class="text-sm text-gray-500">综合评分</div>
          <div class="flex items-center mt-1">
            <el-rate
              v-model="stats.averageRating"
              disabled
              show-score
              allow-half
              text-color="#ff9900"
            />
          </div>
        </div>
        <div class="flex-1">
          <div
            v-for="(rate, index) in stats.ratingDistribution"
            :key="index"
            class="flex items-center mb-1"
          >
            <span class="text-sm mr-2">{{ 5 - index }}星</span>
            <div class="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden">
              <div
                class="h-full bg-orange-500"
                :style="{ width: rate + '%' }"
              ></div>
            </div>
            <span class="text-sm ml-2">{{ rate }}%</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 评价标签筛选 -->
    <div class="review-tags mb-4">
      <el-tag
        v-for="tag in reviewTags"
        :key="tag.name"
        :type="tag.active ? '' : 'info'"
        class="mr-2 mb-2 cursor-pointer"
        @click="toggleTag(tag)"
      >
        {{ tag.name }} ({{ tag.count }})
      </el-tag>
    </div>

    <!-- 评价列表 -->
    <div class="review-list">
      <div
        v-for="review in reviews"
        :key="review.id"
        class="review-item border-b py-4"
      >
        <div class="flex items-start">
          <img :src="review.userAvatar" class="w-8 h-8 rounded-full" />
          <div class="ml-3 flex-1">
            <div class="flex items-center">
              <span class="font-medium">{{ review.userName }}</span>
              <el-rate
                v-model="review.rating"
                disabled
                class="ml-2"
                size="small"
              />
            </div>
            <div class="text-gray-500 text-sm mt-1">{{ review.date }}</div>
            <div class="mt-2">{{ review.content }}</div>

            <!-- 评价图片 -->
            <div
              class="review-images mt-3 grid grid-cols-4 gap-2"
              v-if="review.images && review.images.length"
            >
              <div
                v-for="(image, index) in review.images"
                :key="index"
                class="aspect-square rounded overflow-hidden cursor-pointer"
                @click="previewImage(review.images, index)"
              >
                <img :src="image" class="w-full h-full object-cover" />
              </div>
            </div>

            <!-- 商品规格信息 -->
            <div class="text-sm text-gray-500 mt-2">
              {{ review.specs }}
            </div>

            <!-- 商家回复 -->
            <div
              v-if="review.reply"
              class="mt-3 bg-gray-50 p-3 rounded text-sm"
            >
              <span class="text-orange-500">商家回复：</span>{{ review.reply }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div class="text-center py-4" v-if="hasMore">
      <el-button type="text" @click="loadMore" :loading="loading">
        加载更多
      </el-button>
    </div>
    
    <!-- 暂无评价 -->
    <el-empty v-if="reviews.length === 0" description="暂无评价" />
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import service from "@/api/axios";
import { ElMessage } from "element-plus";

export default {
  name: "ProductReviews",
  props: {
    productId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props) {
    // 默认测试数据
    const defaultStats = {
      averageRating: 4.8,
      ratingDistribution: [95, 3, 1, 0.5, 0.5], // 5星到1星的分布
      tagCounts: {
        "全部": 28,
        "好评": 24,
        "有图": 15,
        "追评": 5
      }
    };

    const defaultReviews = [
      {
        id: 1,
        userName: "用户1",
        userAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
        rating: 5,
        date: "2025-04-15",
        content: "这个商品非常好，质量很好，值得购买。",
        images: [
          "https://img2.baidu.com/it/u=1159203698,2924032871&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
          "https://img2.baidu.com/it/u=486554850,24928460&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
        ],
        specs: "颜色：天青色；规格：12件套",
        reply: "感谢您的购买和评价，欢迎下次光临！"
      }
    ];

    const stats = ref({...defaultStats});

    const reviewTags = ref([
      { name: "全部", count: 0, active: true },
      { name: "好评", count: 0, active: false },
      { name: "有图", count: 0, active: false },
      { name: "追评", count: 0, active: false },
    ]);

    const reviews = ref([]);
    const loading = ref(false);
    const hasMore = ref(true);
    const page = ref(1);
    const pageSize = ref(10);
    const currentTag = ref("全部");

    // 获取评价统计数据
    const fetchReviewStats = async () => {
      try {
        const response = await service.get(`/public/shop/products/${props.productId}/reviews/stats`);
        if (response && response.data) {
          // 确保averageRating是数值类型
          const responseData = response.data;
          let avgRating = responseData.avgRating || responseData.averageRating;
          
          // 确保评分是数值
          if (typeof avgRating !== 'number') {
            avgRating = 5; // 默认评分
          }
          
          // 构建格式化的数据
          const formattedStats = {
            averageRating: avgRating,
            ratingDistribution: responseData.ratingDistribution || defaultStats.ratingDistribution,
            tagCounts: responseData.tags || defaultStats.tagCounts
          };
          
          stats.value = formattedStats;
          
          // 更新标签数量
          if (formattedStats.tagCounts) {
            reviewTags.value.forEach(tag => {
              if (formattedStats.tagCounts[tag.name]) {
                tag.count = formattedStats.tagCounts[tag.name];
              }
            });
          }
        }
      } catch (error) {
        console.error("获取评价统计失败:", error);
        // 使用默认数据
        stats.value = {...defaultStats};
        
        // 使用默认数据更新标签数量
        reviewTags.value.forEach(tag => {
          if (defaultStats.tagCounts[tag.name]) {
            tag.count = defaultStats.tagCounts[tag.name];
          }
        });
      }
    };

    // 获取评价列表
    const fetchReviews = async (reset = false) => {
      if (reset) {
        page.value = 1;
        reviews.value = [];
      }
      
      loading.value = true;
      
      try {
        const params = {
          page: page.value,
          size: pageSize.value,
          tag: currentTag.value !== "全部" ? currentTag.value : undefined
        };
        
        const response = await service.get(`/public/shop/products/${props.productId}/reviews`, { params });
        
        if (response && response.data) {
          let reviewData = response.data;
          
          // 确保获取到的是数组
          if (!Array.isArray(reviewData)) {
            if (reviewData.content && Array.isArray(reviewData.content)) {
              reviewData = reviewData.content;
              hasMore.value = !reviewData.last;
            } else {
              // 如果不是数组也没有content属性，使用默认数据
              reviewData = reset ? [...defaultReviews] : [];
              hasMore.value = false;
            }
          } else {
            // 判断是否还有更多数据
            hasMore.value = reviewData.length === pageSize.value;
          }
          
          // 确保每个评价项都有rating属性且是数值
          reviewData.forEach(review => {
            if (typeof review.rating !== 'number') {
              review.rating = 5; // 默认评分
            }
          });
          
          if (reset) {
            reviews.value = reviewData;
          } else {
            reviews.value = [...reviews.value, ...reviewData];
          }
        } else {
          // 响应成功但没有数据
          if (reset) {
            reviews.value = [...defaultReviews];
          }
          hasMore.value = false;
        }
      } catch (error) {
        console.error("获取评价列表失败:", error);
        // 使用默认评价数据
        if (reset) {
          reviews.value = [...defaultReviews];
        }
        hasMore.value = false;
      } finally {
        loading.value = false;
      }
    };

    const toggleTag = (tag) => {
      reviewTags.value.forEach((t) => (t.active = false));
      tag.active = true;
      currentTag.value = tag.name;
      
      // 重新加载评价列表
      fetchReviews(true);
    };

    const previewImage = (images, index) => {
      // ElementPlus自带的图片预览功能
    };

    const loadMore = async () => {
      if (loading.value || !hasMore.value) return;
      
      page.value++;
      await fetchReviews();
    };

    onMounted(() => {
      // 获取评价数据
      fetchReviewStats();
      fetchReviews(true);
    });

    return {
      stats,
      reviewTags,
      reviews,
      loading,
      hasMore,
      toggleTag,
      previewImage,
      loadMore,
    };
  },
};
</script>

<style scoped>
.review-images img {
  transition: transform 0.2s;
}

.review-images img:hover {
  transform: scale(1.05);
}
</style>
